<template>
  <div ref="tableDiv" class="simpleTable">
    <el-table :data="tableData" header-row-class-name="headerClass">
      <el-table-column
        v-for="(item, index) in tableLabel"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :show-overflow-tooltip="item.showOverflowTooltip"
      >
        <template slot-scope="scope">
          <div v-if="item.type === 'tag'" class="tableTag" align="center" :class="scope.row.className">
            {{ scope.row[item.prop] }}
          </div>
          <div v-if="item.type !== 'tag'">{{ scope.row[item.prop] }}</div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  props: {
    searchData: {
      type: Object,
      default: () => {}
    },
    tableData: {
      type: Array,
      default: () => []
    },
    tableLabel: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {}
  },
  mounted() {
    this.$emit('getTableData')
    this.tableWidthCompute()
  },
  methods: {
    // 自适应table宽度函数
    tableWidthCompute() {
      const _self = this
      var oldWidth = this.$parent.$refs.tableDiv.offsetWidth
      for (const index in this.tableLabel) {
        if (this.tableLabel[index].width) {
          // 检测是否有爷el-col组件并定义xl属性
          if (this.$parent.$parent.xl) {
            // 现table宽=现在div宽*定义table宽/定义div宽
            // 1658为定义时的页面宽
            this.tableLabel[index].width =
              (oldWidth * this.tableLabel[index].width) / ((this.$parent.$parent.xl.span / 24) * 1658)
          } else {
            this.tableLabel[index].width = (document.body.clientWidth * this.tableLabel[index].width) / 1920
          }
        }
      }
      const arr = JSON.parse(JSON.stringify(_self.tableLabel))
      var elementResizeDetectorMaker = require('element-resize-detector') // 导入
      var erd = elementResizeDetectorMaker()
      erd.listenTo(this.$refs.tableDiv, function (element) {
        for (const index in arr) {
          const width = arr[index].width / oldWidth
          if (_self.tableLabel[index].minWidth && element.offsetWidth * width < _self.tableLabel[index].minWidth) {
            _self.tableLabel[index].width = _self.tableLabel[index].minWidth
            continue
          }
          if (_self.tableLabel[index].maxWidth && element.offsetWidth * width > _self.tableLabel[index].maxWidth) {
            _self.tableLabel[index].width = _self.tableLabel[index].maxWidth
            continue
          }
          if (_self.tableLabel[index].width) {
            _self.tableLabel[index].width = element.offsetWidth * width
          }
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.simpleTable {
  /deep/ .el-table td {
    padding: 6px;
    height: 40px;
    color: #000000;
  }
  /deep/ .el-table th {
    padding: 8px 0px;
    background-color: #f5f6f8;
    color: #000000;
  }
}
</style>
